package org.jeecg.common.util.redisson;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @Description:
 * @Author: Planifolia.Van
 * @Date: 2025/1/13 16:43
 */
@Component
public class RedissonLockUtil {

    @Resource
    private RedissonClient redissonClient;

    private final static String RKEY_PREF = "rkey";

    /**
     * 尝试加锁并执行业务逻辑
     *
     * @param lockKey   锁的键
     * @param waitTime  等待锁的时间
     * @param leaseTime 锁的租期时间
     * @param timeUnit  时间单位
     * @param callback  成功后执行的逻辑
     * @param <T>       返回值类型
     * @return 返回执行结果
     */
    public <T> T tryLockAndExecute(String lockKey, long waitTime, long leaseTime, TimeUnit timeUnit, Function<Boolean, T> callback) {
        RLock lock = redissonClient.getLock(RKEY_PREF + lockKey);
        boolean isLocked = false;
        try {
            isLocked = lock.tryLock(waitTime, leaseTime, timeUnit);
        } catch (Exception e) {
            throw new RuntimeException("锁操作失败: " + lockKey, e);
        } finally {
            if (isLocked && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
        return callback.apply(isLocked);
    }
}
